package com.kbbywyclient.presenter;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kbbywyclient.R;
import com.kbbywyclient.app.API;
import com.kbbywyclient.app.Key;
import com.kbbywyclient.data.entity.UnionPayInfo;
import com.kbbywyclient.data.entity.WeChatPayParams;
import com.kbbywyclient.presenter.base.BasePresenter;
import com.kbbywyclient.service.ApiService;
import com.kbbywyclient.service.ApiServiceHelper;
import com.kbbywyclient.ui.contarct.RechargeContract;
import com.kbbywyclient.util.Base64Utils;
import com.kbbywyclient.util.HttpExcUtil;
import com.kbbywyclient.util.LogUtil;
import com.kbbywyclient.util.OkHttpUtils;
import com.kbbywyclient.util.RSAUtil;
import com.kbbywyclient.util.RsaJsonUtil;

import java.io.IOException;

import javax.inject.Inject;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.Observer;

/**
 * Created by cbb on 2017/4/18.
 */

public class RechargePresenter extends BasePresenter implements RechargeContract.Presenter {
    @Inject
    Context mContext;
    @Inject
    ApiService apiService;

    @Inject
    RsaJsonUtil rsaJsonUtil;

    private RechargeContract.View view;

    @Inject
    public RechargePresenter(RechargeContract.View view) {
        this.view = view;
    }


    @Override
    public void getWeChatPayInfo(String SalesID, String LoginKey, String payType, String money) {
        rsaJsonUtil.put("SalesID", SalesID);
        rsaJsonUtil.put("LoginKey", LoginKey);
        rsaJsonUtil.put("payType", payType);
        rsaJsonUtil.put("money", money);

        view.showLoadingDialog(mContext.getString(R.string.loading));
        final OkHttpClient okHttpClient = OkHttpUtils.getOkHttpClient();
        final RequestBody body = new FormBody.Builder().add("params", rsaJsonUtil.getRsaParams()).build();
        final Request request = new Request.Builder().
                url(API.PAY_ADDRESS + "pay/weixin/weixintopay.do").
                post(body).build();
        ApiServiceHelper.
                appointThreadNormal(Observable.create((Observable.OnSubscribe<WeChatPayParams>) subscriber -> {
                    try {
                        Response response = okHttpClient.newCall(request).execute();
                        //服务器响应成功
                        if (response.isSuccessful()) {
                            String source = response.body().string();
                            if (source.startsWith("{")) {
                                //失败，服务器返回的数据没有加密
                                WeChatPayParams weChatPayParams = new WeChatPayParams();
                                JSONObject json = JSON.parseObject(source);
                                weChatPayParams.setStatus(json.getString("status"));
                                weChatPayParams.setMsg(json.getString("msg"));
                                subscriber.onNext(weChatPayParams);
                                subscriber.onCompleted();
                            } else {
                                //成功，服务器返回的数据是加密后的数据，需要解密
                                JSONObject json =
                                        JSON.parseObject(RSAUtil.decryptByPrivateKey(source, Key.privateKey));
                                LogUtil.d(json.toJSONString());
                                WeChatPayParams weChatPayParams =
                                        JSON.parseObject(json.toJSONString(), WeChatPayParams.class);
                                //需要单独设置packageValue,因为服务器返回的key为package，它与java 关键字冲突
                                weChatPayParams.setPackageValue(json.getString("package"));
                                subscriber.onNext(weChatPayParams);
                                subscriber.onCompleted();
                            }
                        } else {
                            subscriber.onError(new RuntimeException("weChat pay error,code:" + response.code()));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        subscriber.onError(e);
                    }
                })).subscribe(new Observer<WeChatPayParams>() {
                    @Override
                    public void onCompleted() {
                        view.closeLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        HttpExcUtil.printError(e);
                        view.closeLoadingDialog();
                    }

                    @Override
                    public void onNext(WeChatPayParams weChatPayParams) {
                        view.onGetWeChatPayInfoSuccess(weChatPayParams);
                    }
                });
    }

    @Override
    public void getUnionPayInfo(String SalesID, String LoginKey, String login_type, String money) {
        rsaJsonUtil.put("SalesID", SalesID);
        rsaJsonUtil.put("LoginKey", LoginKey);
        rsaJsonUtil.put("login_type", login_type);
        rsaJsonUtil.put("money", money);

        view.showLoadingDialog(mContext.getString(R.string.loading));
        final OkHttpClient okHttpClient = OkHttpUtils.getOkHttpClient();
        final RequestBody body = new FormBody.Builder().add("params", rsaJsonUtil.getRsaParams()).build();
        final Request request = new Request.Builder().
                url(API.PAY_ADDRESS + "pay/unionpay/getTn.do").
                post(body).build();
        ApiServiceHelper.
                appointThreadNormal(Observable.create((Observable.OnSubscribe<UnionPayInfo>) subscriber -> {
                    try {
                        LogUtil.d(request.toString());
                        Response response = okHttpClient.newCall(request).execute();
                        if (response.isSuccessful()) {
                            String source = response.body().string();
                            if (source.startsWith("{")) {
                                //失败，服务器返回的数据没有加密
                                final UnionPayInfo unionPayInfo = JSON.parseObject(source, UnionPayInfo.class);
                                subscriber.onNext(unionPayInfo);

                            } else {
                                //成功，服务器返回的数据是加密后的数据，需要解密
                                String decrypt = RSAUtil.decryptByPrivateKey(source, Key.privateKey);
                                final UnionPayInfo unionPayInfo = JSON.parseObject(decrypt, UnionPayInfo.class);
                                //base64解码
                                unionPayInfo.setMsg(Base64Utils.base64Decode(unionPayInfo.getMsg()));
                                subscriber.onNext(unionPayInfo);
                            }
                            subscriber.onCompleted();
                        } else {
                            subscriber.onError(new RuntimeException("union pay error,code:" + response.code()));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        subscriber.onError(e);
                    }
                })).subscribe(new Observer<UnionPayInfo>() {
                    @Override
                    public void onCompleted() {
                        view.closeLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        HttpExcUtil.printError(e);
                        view.closeLoadingDialog();
                    }

                    @Override
                    public void onNext(UnionPayInfo unionPayInfo) {
                        view.onGetUnionPayInfoSuccess(unionPayInfo);
                    }
                });
    }
}
